package com.edu.user.controller;

import com.edu.entity.SysUserInfo;
import com.edu.user.entity.*;
import com.edu.user.service.IModuleService;
import com.edu.vo.Result;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("manage")
public class SysModuleController {

    @Autowired(required = false)
    private IModuleService moduleService;


    @RequestMapping("/module/init")
    public ManageInit initCon(HttpSession session) throws Exception {
        ManageInit init = new ManageInit();
        init.setHomeInfo(new HomeInfo());
        init.setLogoInfo(new LogoInfo());

        SysUserInfo existUser = (SysUserInfo) session.getAttribute("existUser");

//        if (null != existUser ){
//
//            List<Module> moduleList =
//                    service.queryModuleListHierarchyByAccount(existUser.getUserName());
//
//            init.setMenuInfo(moduleList);
//
//        }


//        //测试使用
        List<Module> moduleList = moduleService.queryModuleListHierarchyByAccount("aaa");
        init.setMenuInfo(moduleList);

        return init;
    }


    //    /module/queryTreeNodeListHierarchy
    @RequestMapping("/module/queryTreeNodeListHierarchy")
    public Result queryTreeNodeListHierarchy(String roleId) throws Exception {

        //有层级地查询所有菜单
        List<TreeNodeVO> treeNodeList = moduleService.queryTreeNodeListHierarchy();
        //根据角色编号查询已经授权过的三级菜单
        List<TreeNodeVO> treeNode3List = moduleService.queryThirdTreeNodeListByRoleId(roleId);
        //拿着treeNodeList的三级菜单和已经授权过的三级菜单比对

        //一级菜单
        for (TreeNodeVO m1 : treeNodeList) {
            //展开一级菜单
            m1.setSpread(true);
            List<TreeNodeVO> m2List = m1.getChildren();

            //二级菜单
            for (TreeNodeVO m2 : m2List) {
                List<TreeNodeVO> m3List = m2.getChildren();

                //三级菜单
                for (TreeNodeVO m3 : m3List) {
                    for (TreeNodeVO tree3 : treeNode3List) {
                        if (m3.getId().equals(tree3.getId())) {
                            //如果比对上了，就选中该三级菜单
                            m3.setChecked(true);
                        }

                    }
                }
            }
        }
        return new Result(true, 0, "查询成功", treeNodeList);
    }


    @RequestMapping("module/grant")
    public Result grant(String roleId, @RequestParam("moduleIds[]") List<String> moduleIds) {


        System.out.println(roleId);
        System.out.println(moduleIds);

        return moduleService.grant(roleId, moduleIds);

//        return null;

    }


}
